package com.ruoyi.drone.controller;

import java.math.BigDecimal;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.drone.domain.DroneOrganization;
import com.ruoyi.drone.domain.DroneUserProfile;
import com.ruoyi.drone.mapper.DroneOrganizationMapper;
import com.ruoyi.drone.mapper.DroneUserProfileMapper;
import com.ruoyi.drone.utils.PhotoUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.drone.domain.DroneTask;
import com.ruoyi.drone.domain.DroneTaskExecution;
import com.ruoyi.drone.domain.dto.PilotTaskDetailDTO;
import com.ruoyi.drone.service.IDroneTaskService;
import com.ruoyi.drone.service.IDroneTaskExecutionService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 任务发布Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/drone/task")
public class DroneTaskController extends BaseController
{
    @Autowired
    private IDroneTaskService droneTaskService;

    @Autowired
    private IDroneTaskExecutionService droneTaskExecutionService;

    @Autowired
    private DroneOrganizationMapper droneOrganizationMapper;

    @Autowired
    private DroneUserProfileMapper droneUserProfileMapper;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 查询任务发布列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DroneTask droneTask)
    {
        startPage();
        List<DroneTask> list = droneTaskService.selectDroneTaskList(droneTask);
        return getDataTable(list);
    }

    /**
     * 根据组织ID查询任务发布列表
     */
    @GetMapping("/listByOrg")
    public TableDataInfo listByOrg(HttpServletRequest request)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null) {
            return getDataTable(null);
        }
        
        startPage();
        List<DroneTask> list = droneTaskService.selectDroneTaskListByOrgId(organization.getOrgId());
        return getDataTable(list);
    }


    /**
     * 获取任务发布详细信息
     */
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId)
    {
        return success(droneTaskService.selectDroneTaskByTaskId(taskId));
    }

    /**
     * 新增任务发布（仅组织方）
     */
    @Log(title = "任务发布", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(HttpServletRequest request, @RequestBody DroneTask droneTask)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 检查用户是否为组织方
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null) {
            return error("只有组织方才能发布任务，请先注册组织信息");
        }
        
        // 检查组织状态
        if (!"1".equals(organization.getStatus())) {
            return error("组织信息未通过审核，无法发布任务");
        }
        
        droneTask.setOrgId(organization.getOrgId());
        droneTask .setCreateBy(String.valueOf(userId));
        droneTask.setStatus("1"); // 直接设为已发布状态
        
        return toAjax(droneTaskService.insertDroneTask(droneTask));
    }

    /**
     * 修改任务发布
     */
    @Log(title = "任务发布", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(HttpServletRequest request, @RequestBody DroneTask droneTask)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 查询原任务信息
        DroneTask originalTask = droneTaskService.selectDroneTaskByTaskId(droneTask.getTaskId());
        if (originalTask == null) {
            return error("任务不存在");
        }
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null || !organization.getOrgId().equals(originalTask.getOrgId())) {
            return error("只能修改自己组织的任务");
        }
        
        // 只有待审核和已拒绝状态的任务可以修改
        if (!"0".equals(originalTask.getStatus()) && !"5".equals(originalTask.getStatus())) {
            return error("只有待审核和已拒绝状态的任务可以修改");
        }
        
        droneTask.setUpdateBy(String.valueOf(userId));
        return toAjax(droneTaskService.updateDroneTask(droneTask));
    }

    /**
     * 删除任务发布
     */
    @Log(title = "任务发布", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    public AjaxResult remove(HttpServletRequest request, @PathVariable Long[] taskIds)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null) {
            return error("请先注册组织信息");
        }
        
        // 检查每个任务是否属于该组织
        for (Long taskId : taskIds) {
            DroneTask task = droneTaskService.selectDroneTaskByTaskId(taskId);
            if (task == null || !organization.getOrgId().equals(task.getOrgId())) {
                return error("只能删除自己组织的任务");
            }
            
            // 只有待审核和已拒绝状态的任务可以删除
            if (!"0".equals(task.getStatus()) && !"5".equals(task.getStatus())) {
                return error("只有待审核和已拒绝状态的任务可以删除");
            }
        }
        
        return toAjax(droneTaskService.deleteDroneTaskByTaskIds(taskIds));
    }

    /**
     * 发布任务
     */
    @Log(title = "任务发布", businessType = BusinessType.UPDATE)
    @PutMapping("/publish/{taskId}")
    public AjaxResult publish(HttpServletRequest request, @PathVariable Long taskId)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 查询任务信息
        DroneTask task = droneTaskService.selectDroneTaskByTaskId(taskId);
        if (task == null) {
            return error("任务不存在");
        }
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null || !organization.getOrgId().equals(task.getOrgId())) {
            return error("只能发布自己组织的任务");
        }
        
        // 只有待审核状态的任务可以发布
        if (!"0".equals(task.getStatus())) {
            return error("只有待审核状态的任务可以发布");
        }
        
        return toAjax(droneTaskService.publishTask(taskId));
    }

    /**
     * 取消任务
     */
    @Log(title = "任务发布", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{taskId}")
    public AjaxResult cancel(HttpServletRequest request, @PathVariable Long taskId)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 查询任务信息
        DroneTask task = droneTaskService.selectDroneTaskByTaskId(taskId);
        if (task == null) {
            return error("任务不存在");
        }
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null || !organization.getOrgId().equals(task.getOrgId())) {
            return error("只能取消自己组织的任务");
        }
        
        // 只有已发布和进行中状态的任务可以取消
        if (!"1".equals(task.getStatus()) && !"2".equals(task.getStatus())) {
            return error("只有已发布和进行中状态的任务可以取消");
        }
        
        return toAjax(droneTaskService.cancelTask(taskId));
    }

    /**
     * 完成任务
     */
    @Log(title = "任务发布", businessType = BusinessType.UPDATE)
    @PutMapping("/complete/{taskId}")
    public AjaxResult complete(HttpServletRequest request, @PathVariable Long taskId)
    {
        Long userId = (Long) request.getAttribute("userId");
        
        // 查询任务信息
        DroneTask task = droneTaskService.selectDroneTaskByTaskId(taskId);
        if (task == null) {
            return error("任务不存在");
        }
        
        // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null || !organization.getOrgId().equals(task.getOrgId())) {
            return error("只能完成自己组织的任务");
        }
        
        // 只有进行中状态的任务可以完成
        if (!"2".equals(task.getStatus())) {
            return error("只有进行中状态的任务可以完成");
        }
        
        return toAjax(droneTaskService.completeTask(taskId));
    }

    /**
     * 上传任务图片
     */
    @PostMapping("/upload/image")
    public AjaxResult uploadTaskImage(@RequestParam("file") MultipartFile file)
    {
        try {
            String photoUrl = PhotoUploadUtils.uploadPhoto(file, "task_image", uploadPath);
            System.out.println("图片上传成功 - photoUrl: " + photoUrl);
            AjaxResult result = success(photoUrl);
            System.out.println("图片上传成功 - AjaxResult: " + result);
            return result;
        } catch (Exception e) {
            System.out.println("图片上传失败: " + e.getMessage());
            return error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传任务图片
     */
    @PostMapping("/upload/images")
    public AjaxResult uploadTaskImages(@RequestParam("files") MultipartFile[] files)
    {
        try {
            String[] photoUrls = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                photoUrls[i] = PhotoUploadUtils.uploadPhoto(files[i], "task_image", uploadPath);
            }
            return success(photoUrls);
        } catch (Exception e) {
            return error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除任务图片
     */
    @PostMapping("/delete/image")
    public AjaxResult deleteTaskImage(@RequestParam("photoUrl") String photoUrl)
    {
        try {
            boolean success = PhotoUploadUtils.deletePhoto(photoUrl, uploadPath);
            if (success) {
                return success("删除成功");
            } else {
                return error("删除失败");
            }
        } catch (Exception e) {
            return error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 验证任务图片URL
     */
    @PostMapping("/validate/image")
    public AjaxResult validateTaskImage(@RequestParam("photoUrl") String photoUrl)
    {
        try {
            boolean valid = PhotoUploadUtils.isValidPhotoUrl(photoUrl);
            return success(valid);
        } catch (Exception e) {
            return error("验证失败：" + e.getMessage());
        }
    }

    // ==================== 飞手相关接口 ====================

    /**
     * 飞手查看已发布的任务列表
     */
    @GetMapping("/published")
    public TableDataInfo getPublishedTasks()
    {
        DroneTask task = new DroneTask();
        task.setStatus("1"); // 只查询已发布的任务
        startPage();
        List<DroneTask> list = droneTaskService.selectDroneTaskList(task);
        return getDataTable(list);
    }

    /**
     * 飞手直接接单（仅飞手）
     */
    @Log(title = "飞手接单", businessType = BusinessType.INSERT)
    @PostMapping("/accept/{taskId}")
    public AjaxResult acceptTask(HttpServletRequest request, @PathVariable("taskId") Long taskId)
    {
        Long userId = (Long) request.getAttribute("userId");

        System.out.println("userId = " + userId);

        
        try {
            // 1. 检查用户是否为飞手
            DroneUserProfile pilotProfile = droneUserProfileMapper.selectDroneUserProfileByUserId(userId);
            if (pilotProfile == null) {
                return error("只有飞手才能接单，请先注册飞手信息");
            }
            if (!"1".equals(pilotProfile.getStatus())) {
                return error("飞手档案未通过审核，无法接单");
            }
            
            // 2. 检查任务是否存在且为已发布状态
            DroneTask task = droneTaskService.selectDroneTaskByTaskId(taskId);
            if (task == null) {
                return error("任务不存在");
            }
            if (!"1".equals(task.getStatus())) {
                return error("任务状态不允许接单");
            }
            
            // 3. 检查是否已经接单
            if (!droneTaskExecutionService.checkTaskExecutionUnique(taskId, userId)) {
                return error("您已经接单该任务，不能重复接单");
            }
            
            // 4. 更新任务状态为进行中
            DroneTask updateTask = new DroneTask();
            updateTask.setTaskId(taskId);
            updateTask.setStatus("2"); // 进行中
            updateTask.setUpdateBy(String.valueOf(userId));
            droneTaskService.updateDroneTaskStatus(updateTask);
            
            // 5. 创建执行记录
            DroneTaskExecution execution = new DroneTaskExecution();
            execution.setTaskId(taskId);
            execution.setPilotId(userId);
            execution.setApplicationId(0L); // 简化流程中设置为0，表示直接接单
            execution.setStartTime(DateUtils.getNowDate());
            execution.setStatus("0"); // 进行中
            execution.setCompletionRate(BigDecimal.ZERO);
            execution.setWorkHours(BigDecimal.ZERO);
            execution.setCreateBy(String.valueOf(userId));
            droneTaskExecutionService.insertDroneTaskExecution(execution);
            
            return success("接单成功");
        } catch (Exception e) {
            return error("接单失败：" + e.getMessage());
        }
    }

    /**
     * 飞手查看我的任务
     */
    @GetMapping("/myTasks")
    public TableDataInfo getMyTasks(HttpServletRequest request)
    {
        Long userId = (Long) request.getAttribute("userId");
        startPage();
        List<PilotTaskDetailDTO> list = droneTaskExecutionService.selectPilotTaskDetailList(userId);
        return getDataTable(list);
    }

    /**
     * 飞手查看我的任务详情
     */
    @GetMapping("/myTask/{executionId}")
    public AjaxResult getMyTaskDetail(@PathVariable("executionId") Long executionId)
    {
        PilotTaskDetailDTO taskDetail = droneTaskExecutionService.selectPilotTaskDetailByExecutionId(executionId);
        if (taskDetail == null) {
            return error("任务执行记录不存在");
        }
        return success(taskDetail);
    }
}
